package com.leetcode;

import com.leetcode.common.TreeNode;

/**
 * 404. 左叶子之和
 *
 * @author fy
 * @date 2022/4/20 21:45
 */
public class Solution404_1 {

    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int sum = 0;
        // 这样的逻辑会少迭代几次
        if (root.left != null) {
            if (isLeafNode(root.left)) {
                sum += root.left.val;
            } else {
                sum += sumOfLeftLeaves(root.left);
            }
        }
        if (root.right != null && !isLeafNode(root.right)) {
            sum += sumOfLeftLeaves(root.right);
        }
        return sum;
    }

    /**
     * 判断节点是否是叶子节点
     *
     * @param node
     * @return
     */
    private boolean isLeafNode(TreeNode node) {
        if (node == null) {
            return false;
        }
        return node.left == null && node.right == null;
    }

}
